package psn.kiko.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 *websocket通信类
 */
@Component
@ServerEndpoint(value="/ws/{sid}")
@Slf4j
public class WebSocketSever{
	//会话存储
	private final Map<String,Session> sessionMap=new HashMap<>();
	
	//连接回调
	@OnOpen
	public void onOpen(Session session,@PathParam("sid") String sid){
		log.debug("新连接的websocket客户端：{}",sid);
		sessionMap.put(sid, session);
	}
	
	//收到消息回调
	@OnMessage
	public void onMessage(String message,@PathParam("sid")String sid){
		log.debug("客户端[{}]发来的消息：{}",sid,message);
	}
	
	//连接关闭回调
	@OnClose
	public void onClose(@PathParam("sid")String sid){
		log.debug("客户端[{}]断开连接",sid);
		sessionMap.remove(sid);
	}
	
	//群发
	public void sendMsgToAllClient(String msg) throws IOException{
		Collection<Session> sessions=sessionMap.values();
		for(Session session: sessions){
			session.getBasicRemote().sendText(msg);
		}
	}
}
